import 'package:ai/config/Config.dart';
import 'package:ai/page/text/text_option.dart';
import 'package:ai/response/TextAppResponse.dart';
import 'package:ai/service/TextCreateService.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';

import '../../AppRouter.gr.dart';
import '../../util/CommonUtils.dart';
import '../../util/ToastUtils.dart';

@RoutePage()
class TextCreatePage extends StatefulWidget {
  final int appId;

  const TextCreatePage({super.key, @PathParam("appId") required this.appId});

  @override
  State<TextCreatePage> createState() => _TextCreatePageState();
}

class _TextCreatePageState extends State<TextCreatePage> {
  final ScrollController _scrollController = ScrollController();
  double _appBarOpacity = 0.0;
  final TextCreateService textCreateService = TextCreateService();

  late AppItem data = AppItem.init();

  @override
  void initState() {
    super.initState();
    textCreateService.init(widget.appId).then((result) {
      setState(() {
        data = result;
      });
    });

    _scrollController.addListener(() {
      double offset = _scrollController.offset;
      double opacity = offset / 10;
      if (opacity > 1) opacity = 1;
      setState(() {
        _appBarOpacity = opacity;
      });
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Config.colorB0c9ff.withOpacity(_appBarOpacity),
        centerTitle: true,
        title: Text(data.name),
      ),
      body: Stack(
        children: [
          CommonUtils.getImageAsset(
            "bg_create_title",
            fit: BoxFit.fitWidth,
          ),
          Positioned(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: ListView(
                controller: _scrollController,
                children: List.generate(data.formList.length, (index) {
                  return getFormItem(data.formList[index]);
                }),
              ),
            ),
          )
        ],
      ),
      bottomNavigationBar: BottomAppBar(
        color: Colors.white,
        child: FilledButton(
          style: ButtonStyle(
            backgroundColor: WidgetStateProperty.all(
              Config.primaryColor,
            ),
          ),
          onPressed: () {
            if(checkResult()){
              /// 请求接口
              textCreateService.create(data).then((result){
                if(result.code==0){
                  /// 成功
                  context.router
                      .push(TextWriteRoute(taskId: result.data,textAppId: data.id));
                }else{
                  ToastUtils.error(context, result.msg);
                }
              });
            }
          },
          child: const Text("开始生成"),
        ),
      ),
    );
  }

  Widget getTitle(String title, bool isRequired) {
    var textStyle = TextStyle(
      fontWeight: FontWeight.bold,
      fontSize: 16,
      color: Config.color08070c,
    );
    var requireTextStyle = TextStyle(
      fontWeight: FontWeight.bold,
      fontSize: 16,
      color: Config.colorEc5356,
    );
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: isRequired
          ? RichText(
              text: TextSpan(text: title, style: textStyle, children: [
                TextSpan(text: " * ", style: requireTextStyle),
              ]),
            )
          : Padding(
              padding: const EdgeInsets.only(bottom: 8),
              child: Text(
                title,
                style: textStyle,
              ),
            ),
    );
  }

  Widget getTextField(FormItem formItem, ValueChanged<String> onChanged) {
    return TextField(
      cursorColor: Config.primaryColor,
      minLines: formItem.minLines,
      maxLines: formItem.maxLines,
      onChanged: (value) {
        onChanged(value);
      },
      decoration: InputDecoration(
        focusedBorder: OutlineInputBorder(
          borderSide: BorderSide(width: 2, color: Config.primaryColor),
          borderRadius: const BorderRadius.all(
            Radius.circular(8),
          ),
        ),
        enabledBorder: OutlineInputBorder(
          borderSide: BorderSide(width: 1, color: Config.primaryColor),
          borderRadius: const BorderRadius.all(
            Radius.circular(8),
          ),
        ),
      ),
    );
  }

  Widget getNumberField(ValueChanged<String>? onChanged) {
    return SizedBox(
      height: 48,
      child: TextField(
        minLines: 1,
        maxLines: 1,
        keyboardType: TextInputType.number,
        onChanged: (value) {
          onChanged!(value);
        },
        decoration: InputDecoration(
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(width: 2, color: Config.primaryColor),
            borderRadius: const BorderRadius.all(
              Radius.circular(8),
            ),
          ),
          enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(width: 1, color: Config.primaryColor),
            borderRadius: const BorderRadius.all(
              Radius.circular(8),
            ),
          ),
        ),
      ),
    );
  }

  Widget getFormItemNumber() {
    return Container(
        padding: const EdgeInsets.symmetric(vertical: 8),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            getTitle("结果字数", true),
            const SizedBox(
              height: 8,
            ),
            getNumberField((value) {
              print(value);
            }),
            const SizedBox(
              height: 8,
            ),
          ],
        ));
  }

  Widget getFormItem(FormItem formItem) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          getTitle(formItem.label, formItem.isRequired),
          getContent(formItem),
        ],
      ),
    );
  }

  Widget getContent(FormItem formItem) {
    if (formItem.formType == "radio") {
      return TextOption(
          options: formItem.options,
          type: 0,
          value: formItem.value,
          onChanged: (value) {
            formItem.value = value;
            setState(() {});
          });
    }
    if (formItem.formType == "text") {
      return getTextField(formItem, (value) {
        formItem.value = value;
        setState(() {});
      });
    }
    if (formItem.formType == "select") {
      return TextOption(
          options: formItem.options,
          type: 1,
          value: formItem.value,
          onChanged: (value) {
            formItem.value = value;
            setState(() {});
          });
    }
    return Center(
      child: Text(formItem.formType),
    );
  }

  bool checkResult() {
    for(int i=0;i<data.formList.length;i++){
      FormItem formItem = data.formList[i];
      if(formItem.isRequired && formItem.value.isEmpty){
        ToastUtils.error(context, "请设置${formItem.label}");
        return false;
      }
    }

    return true;
  }
}
